import { defineStore } from 'pinia';
import { usePlanViewApi, type BusinessMonthFilter, type StatisticsCardsResponse, type MonthlyChartResponse, type AreaAnalysisResponse, type AreaItem, type CategoryAnalysisResponse, type CategoryItem } from '/@/api/plans/planView';
import { usePlanDelayViewApi, type PlanDelayStartInput, type PlanDelayStatusOutput } from '/@/api/plans/planDelayView';

interface PlanViewState {
	// 模块化数据（按需加载）
	_statisticsCardsData: StatisticsCardsResponse | null;
	monthlyChartData: MonthlyChartResponse | null;
	delayData: PlanDelayStatusOutput | null;
	
	// 各Tab数据（懒加载）
	areaData: AreaItem[] | null;
	categoryData: CategoryItem[] | null;
	delayAnalysisData: any | null;
	
	// 加载状态
	loadingStates: {
		statisticsCards: boolean;
		monthlyChart: boolean;
		delay: boolean;
		areas: boolean;
		categories: boolean;
		delayAnalysis: boolean;
	};
	
	// 已加载的Tab记录
	loadedTabs: Set<string>;
	
	// 当前查询参数（用于缓存失效）
	currentQueryParams: BusinessMonthFilter | null;
}

export const usePlanViewStore = defineStore('planView', {
	state: (): PlanViewState => ({
		_statisticsCardsData: null,
		monthlyChartData: null,
		delayData: null,
		areaData: null,
		categoryData: null,
		delayAnalysisData: null,
		loadingStates: {
			statisticsCards: false,
			monthlyChart: false,
			delay: false,
			areas: false,
			categories: false,
			delayAnalysis: false,
		},
		loadedTabs: new Set(),
		currentQueryParams: null,
	}),

	getters: {
		// 获取统计卡片数据 (用于StatisticsCards组件)
		statisticsCardsData: (state) => state._statisticsCardsData,
		
		// 获取月度看板数据
		monthlyData: (state) => state.monthlyChartData?.monthlyData || [],
		
		// 检查Tab是否已加载
		isTabLoaded: (state) => (tabName: string) => state.loadedTabs.has(tabName),
		
		// 检查是否有任何加载中的状态
		isAnyLoading: (state) => Object.values(state.loadingStates).some(loading => loading),
	},

  actions: {
        // 计算业务范围（上月26 00:00:00 → 本月25 23:59:59），并格式化为 ISO 本地时间字符串
        // 说明：为减少后端解析开销，前端直接提供显式范围。
        formatDateTimeLocal(date: Date): string {
            const pad = (n: number) => String(n).padStart(2, '0');
            const yyyy = date.getFullYear();
            const MM = pad(date.getMonth() + 1);
            const dd = pad(date.getDate());
            const hh = pad(date.getHours());
            const mm = pad(date.getMinutes());
            const ss = pad(date.getSeconds());
            const ms = String(date.getMilliseconds()).padStart(3, '0');
            return `${yyyy}-${MM}-${dd}T${hh}:${mm}:${ss}.${ms}`;
        },

        getBusinessRange(params?: { workTime?: string; periodType?: 'month'|'quarter'|'year'; year?: string; quarter?: number; rangeStart?: string; rangeEnd?: string; }): { rangeStart: string; rangeEnd: string } | null {
            if (!params) return null;
            if (params.rangeStart && params.rangeEnd) {
                return { rangeStart: params.rangeStart, rangeEnd: params.rangeEnd };
            }
            const type = params.periodType || 'month';
            const pad = (n: number) => String(n).padStart(2, '0');
            const make = (y: number, m: number, d: number, hh: number, mm: number, ss: number, ms: number) => this.formatDateTimeLocal(new Date(y, m, d, hh, mm, ss, ms));
            if (type === 'year') {
                const y = parseInt(params.year || '', 10);
                if (!y) return null;
                return {
                    rangeStart: make(y - 1, 11, 26, 0, 0, 0, 0),
                    rangeEnd: make(y, 11, 25, 23, 59, 59, 999),
                };
            }
            if (type === 'quarter') {
                const y = parseInt(params.year || '', 10);
                const q = params.quarter || 0;
                if (!y || !q) return null;
                switch (q) {
                    case 1:
                        return { rangeStart: make(y - 1, 11, 26, 0, 0, 0, 0), rangeEnd: make(y, 2, 25, 23, 59, 59, 999) };
                    case 2:
                        return { rangeStart: make(y, 2, 26, 0, 0, 0, 0), rangeEnd: make(y, 5, 25, 23, 59, 59, 999) };
                    case 3:
                        return { rangeStart: make(y, 5, 26, 0, 0, 0, 0), rangeEnd: make(y, 8, 25, 23, 59, 59, 999) };
                    case 4:
                        return { rangeStart: make(y, 8, 26, 0, 0, 0, 0), rangeEnd: make(y, 11, 25, 23, 59, 59, 999) };
                }
                return null;
            }
            // month
            const workTime = params.workTime;
            if (!workTime) return null;
            const [y, m] = workTime.split('-').map((s) => parseInt(s, 10));
            if (!y || !m) return null;
            const target = new Date(y, m - 1, 1);
            const prev = new Date(y, m - 2, 1);
            return {
                rangeStart: make(prev.getFullYear(), prev.getMonth(), 26, 0, 0, 0, 0),
                rangeEnd: make(target.getFullYear(), target.getMonth(), 25, 23, 59, 59, 999),
            };
        },
		// 生成缓存键
        generateCacheKey(params: BusinessMonthFilter & { rangeStart?: string; rangeEnd?: string }): string {
            const base = `${params.className || 'all'}_${params.workAreaId || 'all'}`;
            const rs = (params as any).rangeStart || 'all';
            const re = (params as any).rangeEnd || 'all';
            return `${base}_${rs}_${re}`;
        },

		// 检查查询参数是否变化，如果变化则清除缓存
		checkAndClearCache(params: BusinessMonthFilter) {
			const newCacheKey = this.generateCacheKey(params);
			const oldCacheKey = this.currentQueryParams ? this.generateCacheKey(this.currentQueryParams) : null;
			
			if (oldCacheKey !== newCacheKey) {
				this.clearAllData();
				this.currentQueryParams = { ...params };
			}
		},

		// 清除所有数据
		clearAllData() {
			this._statisticsCardsData = null;
			this.monthlyChartData = null;
			this.delayData = null;
			this.areaData = null;
			this.categoryData = null;
			this.delayAnalysisData = null;
			this.loadedTabs.clear();
		},

		// 加载统计卡片数据
		async loadStatisticsCardsData(params: BusinessMonthFilter) {
			// 检查参数变化
			this.checkAndClearCache(params);
			
			// 如果已有数据或正在加载，直接返回
			if (this._statisticsCardsData || this.loadingStates.statisticsCards) {
				return;
			}

			this.loadingStates.statisticsCards = true;
			try {
            const planViewApi = usePlanViewApi();
            const range = this.getBusinessRange(params as any);
            const response = await planViewApi.getStatisticsCards({
                className: params.className,
                workAreaId: params.workAreaId,
                ...(range ?? {}),
            });
				
				if (response.data?.result) {
					this._statisticsCardsData = response.data.result;
				}
			} catch (error) {
				console.error('加载统计卡片数据失败:', error);
				throw error;
			} finally {
				this.loadingStates.statisticsCards = false;
			}
		},

		// 加载月度图表数据
		async loadMonthlyChartData(params: BusinessMonthFilter) {
			// 如果已有数据或正在加载，直接返回
			if (this.monthlyChartData || this.loadingStates.monthlyChart) {
				return;
			}

			this.loadingStates.monthlyChart = true;
			try {
            const planViewApi = usePlanViewApi();
            const range = this.getBusinessRange(params as any);
            const response = await planViewApi.getMonthlyChart({
                className: params.className,
                workAreaId: params.workAreaId,
                ...(range ?? {}),
            });
				
				if (response.data?.result) {
					this.monthlyChartData = response.data.result;
				}
			} catch (error) {
				console.error('加载月度图表数据失败:', error);
				throw error;
			} finally {
				this.loadingStates.monthlyChart = false;
			}
		},

        // 加载延期统计数据
        async loadDelayData(params: BusinessMonthFilter) {
            // 如果已有数据或正在加载，直接返回
            if (this.delayData || this.loadingStates.delay) {
                return;
            }

            this.loadingStates.delay = true;
            try {
                const planDelayViewApi = usePlanDelayViewApi();
                const range = this.getBusinessRange(params as any);
                const delayParams: PlanDelayStartInput = {
                    className: params.className,
                    workAreaId: params.workAreaId,
                    planStart: false, // 默认查询未完成状态
                    ...(range ?? {}),
                } as any;
                const response = await planDelayViewApi.getPlanDelayStatus(delayParams);
                this.delayData = response.data?.result || null;
            } catch (error) {
                console.error('加载延期数据失败:', error);
                throw error;
            } finally {
                this.loadingStates.delay = false;
            }
        },

		// 加载区域数据（Tab懒加载）
		async loadAreaData(params: BusinessMonthFilter, areaIds?: number[]) {
			// 如果已有数据或正在加载，直接返回
			if (this.areaData || this.loadingStates.areas) {
				return;
			}

			this.loadingStates.areas = true;
			try {
            const planViewApi = usePlanViewApi();
            const range = this.getBusinessRange(params as any);
            // 使用新的模块化API获取区域分析数据
            const response = await planViewApi.getAreaAnalysis({
                className: params.className,
                workAreaId: params.workAreaId,
                ...(range ?? {}),
            });
				
				if (response.data?.result?.areas) {
					this.areaData = response.data.result.areas;
				} else {
					this.areaData = [];
				}
				this.loadedTabs.add('areas');
			} catch (error) {
				console.error('加载区域数据失败:', error);
				throw error;
			} finally {
				this.loadingStates.areas = false;
			}
		},

		// 加载分类数据（Tab懒加载）
		async loadCategoryData(params: BusinessMonthFilter, categoryIds?: number[]) {
			// 如果已有数据或正在加载，直接返回
			if (this.categoryData || this.loadingStates.categories) {
				console.log('[DEBUG] 分类数据已存在或正在加载，跳过:', { 
					hasCategoryData: !!this.categoryData, 
					isLoading: this.loadingStates.categories 
				});
				return;
			}

			console.log('[DEBUG] 开始加载分类数据:', params);
			this.loadingStates.categories = true;
			try {
            const planViewApi = usePlanViewApi();
            const range = this.getBusinessRange(params as any);
            // 使用新的模块化API获取分类分析数据
            const response = await planViewApi.getCategoryAnalysis({
                className: params.className,
                workAreaId: params.workAreaId,
                ...(range ?? {}),
            });
				
				console.log('[DEBUG] 分类数据API响应:', response);
				
				if (response.data?.result?.categories) {
					this.categoryData = response.data.result.categories;
					console.log('[DEBUG] 成功设置分类数据:', this.categoryData);
				} else {
					this.categoryData = [];
					console.log('[DEBUG] API响应中无categories数据，设置为空数组');
				}
				this.loadedTabs.add('categories');
			} catch (error) {
				console.error('[ERROR] 加载分类数据失败:', error);
				throw error;
			} finally {
				this.loadingStates.categories = false;
			}
		},

        // 加载延期分析数据（Tab懒加载）
        async loadDelayAnalysisData(params: BusinessMonthFilter) {
            // 如果已有数据或正在加载，直接返回
            if (this.delayAnalysisData || this.loadingStates.delayAnalysis) {
                return;
            }

            this.loadingStates.delayAnalysis = true;
            try {
                const planDelayViewApi = usePlanDelayViewApi();
                
                // 获取延期图表数据
                const range = this.getBusinessRange(params as any);
                const chartParams = {
                    className: params.className,
                    workAreaId: params.workAreaId,
                    planStart: false, // 默认查询未完成状态
                    ...(range ?? {}),
                } as any;

                const [areaDelayRes, categoryDelayRes] = await Promise.all([
                    planDelayViewApi.getAreaDelayCharts(chartParams),
                    planDelayViewApi.getClassDelayCharts(chartParams)
                ]);

				this.delayAnalysisData = {
					areaDelayCharts: areaDelayRes.data?.result || {},
					categoryDelayCharts: categoryDelayRes.data?.result || {},
				};
				
				this.loadedTabs.add('delay');
			} catch (error) {
				console.error('加载延期分析数据失败:', error);
				throw error;
			} finally {
				this.loadingStates.delayAnalysis = false;
			}
		},

		// 刷新所有数据
		async refreshAllData(params: BusinessMonthFilter) {
			this.clearAllData();
			await Promise.all([
				this.loadStatisticsCardsData(params),
				this.loadMonthlyChartData(params),
				this.loadDelayData(params)
			]);
		},

		// 标记Tab为已加载
		markTabAsLoaded(tabName: string) {
			this.loadedTabs.add(tabName);
		},
	},
});
